/**
 * Created by qijialin on 2016/12/19.
 */

var versionFlowBaseUrl = serverPath + 'versionProcess/findVersionProcess';
var versionFlowFromToUrl = serverPath + 'versionProcess/findVersionProcessDetail';
var versionFlowForTypeUrl = serverPath + 'versionProcess/queryObjectTypeByVersionId';
var versionFlowAllTypeUrl = serverPath + 'versionProcess/findAllObjectType';
var versionFlowDeleteUrl = serverPath + 'versionProcess/delete';
var versionFlowCopyUrl = serverPath + 'versionProcess/copyVersion';
var versionFlowUpdateTypeUrl = serverPath + 'versionProcess/updateDB';
var versionFlowAuthorityUrl = serverPath + 'authorities/findAuthorityDetail';
var versionFlowQueryUserGroupUrl = serverPath + 'authorities/findUserGroupsByAid';
var versionFlowQueryAccessUrl = serverPath + 'authorities/query';
var versionFlowStepStatusChangeUrl= serverPath + 'versionProcess/updateVersionStatusChange';

var vfCopyDivIndex = 0;
var vfFromToDivIndex = 0;
var vfFromToAuthorityDivIndex = 0;
var vfObjectEditDivIndex = 0;
var operate = 0;
//版本流的当前step
var nowVFstepJson = null;
var firstLoad = true;


//加载的时候运行
$(function () {
    initPageSize();
    InitData();

    //复制 版本流 按钮事件
    $('#vfCopy').click(function () {
        var url = "VersionFlowCopy.html";
        $("#VFCopyDiv").load(url, function () {
            operate = 1;
            $('#ObjectTypeTable').bootstrapTable();
        });
        vfCopyDivIndex = ibcpLayer.ShowDiv($("#VFCopyDiv"), '复制版本流', '375px', '300px');
    });

    //删除 版本流 对象编辑 按钮事件
    $('#vfDelete').click(function () {
        operate = 2;
        //判断是否是最后一行数据了
        var dRows = $('#VersionFlowList').bootstrapTable('getData');
        if(dRows.length<=1){
            ibcpLayer.ShowMsg('禁止删除最后一行数据！');
            return;
        }

        var vfSel = $('#VersionFlowList').bootstrapTable('getSelections');
        var vfDelId = vfSel[0].id;
        var vfDelMsg = vfSel[0].code + '-' + vfSel[0].name;
        ibcpLayer.ShowConfirm('您确认要删除版本流 : ' + vfDelMsg, function testFun() {
            VFDelete(vfDelId);
        });
    });


    //版本流关联对象编辑 按钮事件
    $('#vfObjectEdit').click(function () {
        var url = "ObjectList.html";
        $("#VFObjectEditDiv").load(url, function () {
            operate = 4;
            $('#ObjectTypeTable').bootstrapTable();
            var nowObjects = $('#ConnectObjectList').bootstrapTable('getData');
            LoadVFObjectList(nowObjects);
        });
        vfObjectEditDivIndex = ibcpLayer.ShowDiv($("#VFObjectEditDiv"), '修改版本流关联对象类型', '375px', '500px');
    });

    ////版本流列表数据行单击事件 on click
    //$('#VersionFlowList').on('click-row.bs.table', function (e, row, element){
    //行选择事件 on Check
    $('#VersionFlowList').on('check.bs.table', function (e, row){
        //拿到行选中的数据
        var selId = row["id"];
        var selDesc = row["description"];
        //刷新右边的数据显示
        $("#VersionCode").val(row["code"]);
        $("#VersionName").val(row["name"]);
        $("#VersionDescribe").val(selDesc);
        LoadVersionFlowOtherInfo(selId);

        //设置按钮状态
        if(firstLoad){
            firstLoad = false;
            initPageSize();
        }
    });
});


//初始加载数据
function InitData(){
    LoadVersionFlowBaseInfo();
    //LoadTable();
    //LoadJsonData();
}

function LoadTable(){
    $("#VersionFlowList").bootstrapTable({
        url: versionFlowBaseUrl,         //请求后台的URL（*）
        method: 'get',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: false,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: {},//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber:1,                       //初始化加载第一页，默认第一页
        pageSize: 50,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: true,                //是否启用点击选中行
        height: 600,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        uniqueId: "id",                     //每一行的唯一标识，一般为主键列
        cardView: false,                    //是否显示详细视图
        detailView: false,                   //是否显示父子表
        columns: [{
            field: 'id',
            title: '序号'
        }, {
            field: 'code',
            title: '代码'
        }, {
            field: 'name',
            title: '名称'
        }, {
            field: 'description',
            title: '描述'
        }],
        responseHandler:function(res) {
            var data = {
                "total": 500,
                "rows": res.data
            }

            return data;
        },
        rowStyle:function rowStyle(row, index) {
            return {
                css: {"height": "30px"}
            };
        }
    });
}

function LoadJsonData(){

    var dataResult={"errorCode":0,
        "data":[{"id":2,"code":"vf001","name":"通用版本流","description":"通用的版本流控制规则","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":161,"code":"12345","name":"1","description":"1","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":162,"code":"2","name":"2","description":"2","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":163,"code":"3","name":"3","description":"3","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":164,"code":"4","name":"4","description":"5","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":165,"code":"6","name":"6","description":"6","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":166,"code":"7","name":"7","description":"7","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":167,"code":"8","name":"8","description":"8","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":168,"code":"9","name":"9","description":"9","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":169,"code":"0","name":"0","description":"0","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null},
            {"id":170,"code":"55","name":"55","description":"55","objTypeId":0,"typeName":null,"typeDescription":null,"fromId":0,"toId":0,"aid":0,"authName":null,"fromName":null,"toName":null,"objId":0,"hisId":0,"tableName":null}]};

    $("#VersionFlowList").bootstrapTable({
        data:dataResult.data
    });
    //$("#VersionFlowList").bootstrapTable('load', dataResult.data);
}

//加载左侧版本流基本信息
function LoadVersionFlowBaseInfo(){
    $('#vfCopy').attr("disabled", true);
    $('#vfDelete').attr("disabled", true);
    $('#vfObjectEdit').attr("disabled", true);

    $.ajax({
        url: versionFlowBaseUrl,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        //async: false,
        success: function (result) {
            var data = result.data;
            $("#VersionFlowList").bootstrapTable('load', data);

            if(data.length >0){
                $('#vfCopy').attr("disabled", false);
                $('#vfObjectEdit').attr("disabled", false);
                if(data.length >1) {
                    $('#vfDelete').attr("disabled", false);
                }
                var vfId = data[0].id;
                var vfDesc = data[0].description;
                //设置选中行
                $('#VersionFlowList').bootstrapTable('check', 0);
                //$("#VersionDescribe").html(vfDesc);
                //LoadVersionFlowOtherInfo(vfId);
            }
        },
        error: function () {
            //alert(1111);
        }

    });
}

//根据版本流ID 获取 其相关信息 状态变更流程 关联对象
function LoadVersionFlowOtherInfo(vfId){
    LoadVersionFlowFromToInfo(vfId);
    LoadVersionFlowForTypeInfo(vfId);
}

//加载版本流流程信息
function LoadVersionFlowFromToInfo(vfId){
    var datas = {'id':vfId};
    $.ajax({
        url: versionFlowFromToUrl,
        data: datas,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        //async: false,
        success: function (result) {
            var data = result.data;
            $("#VersionFlowDetail").bootstrapTable('load', data);
        },
        error: function () {
            //alert(1111);
        }

    });
}

//加载版本流 关联的对象类型信息
function LoadVersionFlowForTypeInfo(vfId){
    var datas = {'id':vfId};
    $.ajax({
        url: versionFlowForTypeUrl,
        data: datas,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        //async: false,
        success: function (result) {
            var data = result.data;
            $("#ConnectObjectList").bootstrapTable("load",data);
        },
        error: function () {
            //alert(1111);
        }

    });
}

//删除版本流
function VFDelete(vfId){
    var datas = {'id':vfId};
    ibcpAjax.Delete(versionFlowDeleteUrl,datas,true,function(){
        ibcpLayer.ShowOK('删除成功！');
        InitData();
    });
}

//自动消失的提示消息
function ShowMsg(msgInfo){
    layer.msg(msgInfo, {
        icon: 1,
        time: 1000, //1秒关闭（如果不配置，默认是3秒）
        zIndex: layer.zIndex //重点1
    });
}

/********************************************************************** 初始化 **********************************************************************/

function initPageSize(){
    var wheight = $('#pieceLeft').height() -  4;
    var rtHeight = (wheight - 180)/2;
    $('#VersionFlowList').bootstrapTable('refreshOptions',{height:wheight - 57});
    $('#VersionFlowDetail').bootstrapTable('refreshOptions',{height:rtHeight});
    $('#ConnectObjectList').bootstrapTable('refreshOptions',{height:rtHeight});
}

$(window).resize(function(){
    initPageSize();
});

//格式化操作列
function operateFormatter(value,row,index){
    return[
        '<div>',
        '<a class="like" href="javascript:void(0)" title="修改权限">',
        '<i class="glyphicon glyphicon-edit"></i>',
        '</a>',
        '</div>'
    ].join('');
}

//操作列事件
window.operateEvents = {
    'click .like': function (e, value, row, index) {
        loadVFSCPageContent(JSON.stringify(row));
    }
}


/**********************************************************************   版本流关联对象    *******************************************************************/

//加载版本流 关联对象类型 弹出层数据
//并勾选当前已关联的对象类型
function LoadVFObjectList(oldObjs){
    $.ajax({
        url: versionFlowAllTypeUrl,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        //async: false,
        success: function (result) {
            //列出所有的对象类型
            var data = result.data;
            $("#ObjectTypeTable").bootstrapTable("load",data);

            //勾选已关联的对象类型
            if(oldObjs.length > 0){
                for(var i = 0;i<oldObjs.length;i++)
                {
                    var id = oldObjs[i].objTypeId;
                    $("#ObjectTypeTable").bootstrapTable("checkBy", {field:"id", values:[id]})
                }
            }

        },
        error: function () {
            //alert(1111);
        }

    });
}

/*版本流 关联对象 弹出层 保存事件*/
function ObjectSave(){
    var vfId = $("#VersionFlowList").bootstrapTable("getSelections")[0].id;
    var objs = $("#ObjectTypeTable").bootstrapTable("getAllSelections");
    var objIds = new Array();
    for(var i=0;i<objs.length;i++){
        objIds[i]=objs[i].id;
    }
    var datas = {'versionId':vfId,'typeIdList':objIds };
    $.ajax({
        url: versionFlowUpdateTypeUrl,
        data:datas,
        type: 'put',
        traditional: true,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        async: false,
        success: function (result) {
            var errCode = result.errorCode;
            if (errCode == 0) {
                ShowMsg('操作成功');
                LoadVersionFlowForTypeInfo(vfId);
                layer.close(vfObjectEditDivIndex);
            }
            else {
                ShowMsg('操作失败');
                layer.close(vfObjectEditDivIndex);
            }
        },
        error: function () {
            alert('服务器异常');
        }

    });
}

//版本流 关联对象 弹出层 取消事件
function ObjectCancel(){
    //$('#ObjectTypeTable').bootstrapTable('resetView');
    layer.close(vfObjectEditDivIndex);
}


/**********************************************************************   版本流Copy    *******************************************************************/

//复制版本流确认按钮事件
function CopySave(){
    var vfSel = $('#VersionFlowList').bootstrapTable('getSelections');
    var oldId = vfSel[0].id;
    var newCode = $('#newVersionFlowCode').val();
    var newName = $('#newVersionFlowName').val();
    var newDesc = $('#newVersionFlowDescribe').val();

    if(newCode == ''){
        ibcpLayer.ShowTips("请填入代码！",$('#newVersionFlowCode'));
        return;
    }
    if(newName == ''){
        ibcpLayer.ShowTips("请填入名称！",$('#newVersionFlowName'));
        return;
    }


    var datas = {"oldId":oldId,"code":newCode,"name":newName,"description":newDesc };
    $.ajax({
        url: versionFlowCopyUrl,
        data: datas,
        type: 'put',
        traditional: true,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        async: false,
        //async: false,
        success: function (result) {
            var errCode = result.errorCode;
            if (errCode == 0) {
                ShowMsg("Copy 成功！");
                var newId = result.id;
                //成功处理
                layer.close(vfCopyDivIndex);
                //定位到新行刷新数据显示
                InitData();
                $("#VersionFlowList").bootstrapTable("checkBy", {field:"id", values:[newId]});
            }
            else{
                ShowMsg("Copy 失败！");
                layer.close(vfCopyDivIndex);
            }
        },
        error: function () {

        }
    });
}

//复制版本流取消按钮事件
function CopyCancel(){
    layer.close(vfCopyDivIndex);
}

/**********************************************************************   版本流状态变更详细画面    *******************************************************************/

//Write contents into 'VersionFlowStateChange' page
//加载详细信息画面
function loadVFSCPageContent(content){
    'use strict';

    try{
        nowVFstepJson = JSON.parse(content);
        var url = "VersionFlowStateChange.html";
        $("#VFFromToDiv").load(url, function () {
            operate = 1;
            $('#JurisdictionUserGroup').bootstrapTable();
            var aid =nowVFstepJson.aid;
            getUserGroupList(aid);
            getDataForVFSCPage(nowVFstepJson);
            getCurrentAccess(aid)
        });
        vfFromToDivIndex = ibcpLayer.ShowDiv($('#VFFromToDiv'), '编辑权限', '550px', '550px');

    }catch(e){
        alert(e);
    }
}

//Get Data For 'VersionFlowStateChange' page
//显示From To 信息
function getDataForVFSCPage(result){
    'use strict';
    $('#StateFrom').val(result.fromName);
    $('#StateTo').val(result.toName);
}

//Get Data For Users' Form
//显示用户组信息
function getUserGroupList(aid){
    'use strict';
    var datas = {'aid':aid};
    $.ajax({
        url: versionFlowQueryUserGroupUrl,
        data: datas,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        //async: false,
        success: function (result) {
            var data = result.data;
            $("#JurisdictionUserGroup").bootstrapTable('load', data);
        },
        error: function () {
            alert(1111);
        }
    });
}

//权限的描述新
function getCurrentAccess(aid){
    'use strict';
    var datas = {'auid':aid};
    $.ajax({
        url: versionFlowQueryAccessUrl,
        data: datas,
        xhrFields: { witchCredentials:true},
        dataType: "json",
        success: function(result) {
            var data = result.data;
            $('#Jurisdiction').val(data.description);
        },
        error: function () {
            alert('getCurrentAccess error');
        }
    });
}

//权限选择按钮事件
function VFStepAuthoritySelect(){
    ShowAuthority();
}

//权限选择按钮事件
function VFStepOK(){
        var datas = {'fromId':nowVFstepJson.fromId,'toId':nowVFstepJson.toId,'aid':nowVFstepJson.aid,'versionId':nowVFstepJson.id};
        //修改
        $.ajax({
            url: versionFlowStepStatusChangeUrl,
            data: datas,
            type: 'put',
            traditional: true,
            xhrFields:{ withCredentials:true},
            dataType: "json",
            async: false,
            //async: false,
            success: function (result) {
                var errCode = result.errorCode
                if (errCode == 0) {
                    layer.close(vfFromToDivIndex);
                    var vfSel = $('#VersionFlowList').bootstrapTable('getSelections');
                    var vfId = vfSel[0].id;
                    LoadVersionFlowFromToInfo(vfId);
                    ShowMsg("权限修改 成功！");
                }
                else{
                    ShowMsg("权限修改 失败！");
                }
            },
            error: function () {

            }
        });
}

function ShowAuthority(){
    var url = "JurisdictionCheck.html";
    $("#VFFromToAuthorityDiv").load(url, function () {
        operate = 0;
        nowAuId = 0;
        $('#VFFTAuthorityTable').bootstrapTable();
        LoadVFCAuthority('');
    });
    vfFromToAuthorityDivIndex = ibcpLayer.ShowDiv($("#VFFromToAuthorityDiv"), '权限查询', '800px', '500px');
}
//权限选择取消按钮事件
function VFStepCancel(){
    layer.close(vfFromToDivIndex);
}

/**********************************************************************   版本流状态变更需要的权限 查询    *******************************************************************/



//加载所有的权限列表
function LoadVFCAuthority(str){
    var datas ={'str':str};
    $.ajax({
        url: versionFlowAuthorityUrl,
        data:datas,
        xhrFields:{ withCredentials:true},
        dataType: "json",
        //async: false,
        success: function (result) {
            //列出所有的对象类型
            var data = result.data;
            $("#VFFTAuthorityTable").bootstrapTable("load",data);

        },
        error: function () {
            alert('权限服务异常');
        }
    });
}

function VFASearch(){
    var condition = $('#txtVFACondition').val();
    if(condition == undefined){condition='';}
    LoadVFCAuthority(condition);
}

//版本流权限选择确认按钮事件
function VFASave(){
    var selAU = $("#VFFTAuthorityTable").bootstrapTable("getSelections");
    nowVFstepJson.aid = selAU[0].id;
    $('#Jurisdiction').val(selAU[0].description);
    getUserGroupList(nowVFstepJson.aid);
    layer.close(vfFromToAuthorityDivIndex);
}

//版本流权限选择取消按钮事件
function VFACancel(){
    //$("#VFFTAuthorityTable").bootstrapTable("refresh");
    layer.close(vfFromToAuthorityDivIndex);
}

